package com.pb.infra.auth.service;

import com.github.pagehelper.PageInfo;
import com.pb.infra.oth.util.JwtTokenConfig;
import com.pb.infra.oth.entity.common.Result;
import com.pb.infra.auth.entity.pbsys.*;
import com.pb.infra.oth.exception.AppAuthException;
import com.pb.infra.oth.exception.ErrorCode;
import com.pb.infra.auth.mapper.custom.PriviCorpCustomMapper;
import com.pb.infra.auth.mapper.pbsys.*;
import com.pb.infra.oth.service.SequenceGeneratorService;
import com.pb.infra.oth.util.Constant;
import com.pb.infra.oth.util.DateTimeUtil;
import io.jsonwebtoken.Claims;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * 法人管理
 * @author liudebao
 * @date 2020/1/1
 */
@Service
public class PriviCorpService {

    /**
     * 多表DAO映射
     */
    @Resource
    private PriviCorpCustomMapper priviCorpCustomMapper;

    /**
     * 法人单表DAO映射
     */
    @Resource
    private PriviCorpMapper priviCorpMapper;

    /**
     * 法人菜单表DAO映射
     */
    @Resource
    private PriviCorpMenuMapper priviCorpMenuMapper;

    /**
     * 序号自动生成逻辑层
     */
    @Resource
    private SequenceGeneratorService sequenceGeneratorService;

    /**
     * 角色表DAO映射
     */
    @Resource
    private PriviRoleMapper roleMapper;

    /**
     * 系统密码策略表DAO映射
     */
    @Resource
    private MetaPriviPasswdPolicyMapper metaPriviPasswdPolicyMapper;

    /**
     * 法人密码策略表DAO映射
     */
    @Resource
    private PriviPasswdPolicyMapper priviPasswdPolicyMapper;

    /**
     * jwttoken配置类
     */
    @Resource
    private JwtTokenConfig jwtTokenConfig;

    /**
     * 读取法人信息
     * @param map 请求参数
     * @return Result 返回数据
     */
    public Result queryCorps(Map<String, Object> map) {
        List<Map<String, Object>> list = priviCorpCustomMapper.getCorpMenus(map);
        return Result.ok(new PageInfo(list).getTotal(), list);
    }

    /**
     * 查询管理法人
     * @return Result 返回数据
     */
    public Result queryManageCorp() {
        return Result.ok(priviCorpCustomMapper.queryManageCorp());
    }

    /**
     * 新建法人
     * @param priviCorp 法人实体类
     * @return 返回数据
     */
    @Transactional
    public Map<String, Object> addCorp(PriviCorp priviCorp, HttpServletRequest request) {
        Map<String, Object> map2 = new HashMap<>();
        try {
            String token = request.getHeader(jwtTokenConfig.getHeader());
            Claims claims = jwtTokenConfig.getClaimByToken(token);
            String userId = (String)claims.get(jwtTokenConfig.getSub());
            PriviCorpExample priviCorpExample = new PriviCorpExample();
            PriviCorpExample.Criteria criteria = priviCorpExample.createCriteria();
            criteria.andCorpNoEqualTo(priviCorp.getCorpNo());
            /*
             * 法人编号是否重复
             */
            List<PriviCorp> list = priviCorpMapper.selectByExample(priviCorpExample);
            if (list != null && list.size() > 0) {
                throw new AppAuthException(ErrorCode.ErrorCodeEnum.ACCESS_TABLE_KEY);
            }
            //String seqId = sequenceGeneratorService.getNextIdStr("CORP", "CORP");
            priviCorp.setCorpId(priviCorp.getCorpNo());
            priviCorp.setCreateUser(userId);
            priviCorp.setUpdateUser(userId);
            priviCorp.setCreateTime(DateTimeUtil.getStrFromNewDate());
            priviCorp.setUpdateTime(DateTimeUtil.getStrFromNewDate());
            //新增法人
            priviCorpMapper.insertSelective(priviCorp);
            String roleId = sequenceGeneratorService.getNextIdStr("ROLE", "ROLE");
            PriviRole priviRole = new PriviRole();
            priviRole.setCorpId(priviCorp.getCorpNo());
            priviRole.setRoleId(roleId);
            priviRole.setRoleName(Constant.ROLE_ADMIN);
            priviRole.setCnName(Constant.ROLE_ADMIN_NAME);
            priviRole.setCreateUser(userId);
            priviRole.setCreateTime(DateTimeUtil.getStrFromNewDate());
            priviRole.setUpdateUser(userId);
            priviRole.setUpdateTime(DateTimeUtil.getStrFromNewDate());
            //新增管理角色
            roleMapper.insertSelective(priviRole);
            //新增默认密码策略
            MetaPriviPasswdPolicyExample metaPriviPasswdPolicyExample = new MetaPriviPasswdPolicyExample();
            MetaPriviPasswdPolicyExample.Criteria criteria1 = metaPriviPasswdPolicyExample.createCriteria();
            criteria1.andActiveFlagEqualTo(Constant.EXIST);
            metaPriviPasswdPolicyExample.setOrderByClause("PASSWD_POLICY_ID asc");
            List<MetaPriviPasswdPolicy> list1 = metaPriviPasswdPolicyMapper.selectByExample(metaPriviPasswdPolicyExample);
            for (int k = 0; k < list1.size(); k++) {
                PriviPasswdPolicy priviPasswdPolicy = new PriviPasswdPolicy();
                String policyId = sequenceGeneratorService.getNextIdStr("POLICY", "CPP");
                priviPasswdPolicy.setPasswdPolicyId(policyId);
                priviPasswdPolicy.setPasswdPolicyName(list1.get(k).getPasswdPolicyName());
                priviPasswdPolicy.setActiveDays(list1.get(k).getActiveDays());
                priviPasswdPolicy.setActiveFlag(list1.get(k).getActiveFlag());
                priviPasswdPolicy.setCorpId(priviCorp.getCorpNo());
                priviPasswdPolicy.setLockFlag(list1.get(k).getLockFlag());
                priviPasswdPolicy.setMaxRetryTimes(list1.get(k).getMaxRetryTimes());
                priviPasswdPolicy.setMinLength(list1.get(k).getMinLength());
                priviPasswdPolicy.setPasswdRule(list1.get(k).getPasswdRule());
                priviPasswdPolicy.setWarnDays(list1.get(k).getWarnDays());
                if (k == 0) {
                    priviPasswdPolicy.setUseFlag(Constant.EXIST);
                } else {
                    priviPasswdPolicy.setUseFlag(Constant.OK);
                }
                priviPasswdPolicy.setCreateUser(userId);
                priviPasswdPolicy.setCreateTime(DateTimeUtil.getStrFromNewDate());
                priviPasswdPolicy.setUpdateUser(userId);
                priviPasswdPolicy.setUpdateTime(DateTimeUtil.getStrFromNewDate());
                priviPasswdPolicyMapper.insertSelective(priviPasswdPolicy);
            }
            map2.put("code", Constant.OK);
            map2.put("msg", Constant.INSERT_OK_MSG);
        } catch (AppAuthException e) {
            map2.put("msg", e.getMessage());
            map2.put("code", e.getCode());
        }
        return map2;
    }

    /**
     * 修改法人
     * @param priviCorp 法人实体类
     */
    @Transactional
    public void editCorp(PriviCorp priviCorp, HttpServletRequest request) {
        String token = request.getHeader(jwtTokenConfig.getHeader());
        Claims claims = jwtTokenConfig.getClaimByToken(token);
        String userId = (String)claims.get(jwtTokenConfig.getSub());
        priviCorp.setUpdateUser(userId);
        priviCorp.setUpdateTime(DateTimeUtil.getStrFromNewDate());
        priviCorpMapper.updateByPrimaryKeySelective(priviCorp);
    }

    /**
     * 删除法人
     * @param paramMap 请求参数
     */
    @Transactional
    public boolean removeCorp(List<String> paramMap) {
        Map<String, Object> map = new HashMap<>();
        map.put("list", paramMap);
        List<Map<String, Object>> list = priviCorpCustomMapper.queryCorpUsers(map);
        if (list != null && list.size() > 0) {
            return false;
        } else {
            for (String corpId : paramMap) {
                PriviCorp priviCorp = new PriviCorp();
                priviCorp.setCorpId(corpId);
                priviCorp.setDeleteFlag(Constant.EXIST);
                priviCorpMapper.updateByPrimaryKeySelective(priviCorp);
            }
            return true;
        }
    }

    /**
     * 恢复法人
     * @param paramMap 请求参数
     */
    @Transactional
    public void resumeCorp(List<String> paramMap) {
        for (String corpId : paramMap) {
            PriviCorp priviCorp = new PriviCorp();
            priviCorp.setCorpId(corpId);
            priviCorp.setDeleteFlag(Constant.OK);
            priviCorpMapper.updateByPrimaryKeySelective(priviCorp);
        }
    }

    /**
     * 查询法人菜单
     * @param paramMap 请求参数
     * @return 返回数据
     */
    public Result queryCorpMenus(Map<String, Object> paramMap) {
        List<Map<String, Object>> menuList = priviCorpCustomMapper.queryCorpMenus(paramMap);
        for (Map<String, Object> menu : menuList) {
            menu.put("checked", Integer.parseInt(menu.get("checked").toString()) == 1);
        }
        return Result.ok(menuList);
    }

    /**
     * 保存法人菜单信息
     * @param paramMap 请求参数
     */
    @Transactional
    public void addCorpMenu(Map<String, Object> paramMap, HttpServletRequest request) {
        String token = request.getHeader(jwtTokenConfig.getHeader());
        Claims claims = jwtTokenConfig.getClaimByToken(token);
        String userId = (String)claims.get(jwtTokenConfig.getSub());
        String corpId = paramMap.get("corpId").toString();
        PriviCorpMenuExample priviCorpMenuExample = new PriviCorpMenuExample();
        PriviCorpMenuExample.Criteria criteria = priviCorpMenuExample.createCriteria();
        criteria.andCorpIdEqualTo(corpId);
        priviCorpMenuMapper.deleteByExample(priviCorpMenuExample);
        for (String menuId : (List<String>) paramMap.get("menuIds")) {
            PriviCorpMenu priviCorpMenu = new PriviCorpMenu();
            priviCorpMenu.setMenuId(menuId);
            priviCorpMenu.setCorpId(corpId);
            priviCorpMenu.setCreateTime(DateTimeUtil.getStrFromNewDate());
            priviCorpMenu.setCreateUser(userId);
            priviCorpMenu.setUpdateTime(DateTimeUtil.getStrFromNewDate());
            priviCorpMenu.setUpdateUser(userId);
            priviCorpMenuMapper.insertSelective(priviCorpMenu);
        }
    }

}
